<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 订单管理
 */
namespace app\ais\model;
use app\common\model\SystemUserLevel;
use app\common\facade\WechatPay;
use think\Model;

class AisOrder extends Model{


    public function store(){
        return $this->hasOne('AisStore','id','store_id');
    }


    public function conponUser(){
        return $this->hasOne('AisCouponUser','id','coupon_user_id');
    }

    public function user(){
        return $this->hasOne('app\common\model\SystemUser','id','uid');
    }
    /**
     * 创建订单
     * @param array $param
     * @return void
     */
    public static function addOrder(array $param){
        $data                      = [];
        $data['member_miniapp_id'] = $param['member_miniapp_id'];
        $data['store_id']          = $param['store_id'];
        $data['store_chain_id']    = $param['store_chain_id'];
        $data['parent_store_id']   = $param['parent_store_id'] ?? 0;
        $data['uid']               = $param['uid'];
        $data['coupon_user_id']    = $param['user_couponr_id'];
        $data['order_no']          = $param['order_no'];
        $data['amount']            = $param['money'];   //输入金额
        $data['price']             = $param['price'];   //实际金额
        $data['coupon_cache']      = empty($param['coupon_cache'])?'':json_encode($param['coupon_cache']);  //留存优惠券
        $data['state']             = 0;
        $data['update_time']       = time();
        return self::insertGetId($data);
    }

  /**
     * 计算器付款价格
     * @param array $param  [计算参数]
     * @return type
     */
    public static function countPrice(array $param){
        $money = floatval($param['money']);  //用户默认付款价
        //我的优惠券
        $coupon_user = [];
        $coupon_user['member_miniapp_id'] = $param['member_miniapp_id'];
        $coupon_user['store_id']          = $param['store_id'];
        $coupon_user['id']                = $param['user_couponr_id'];
        $coupon_user['uid']               = $param['uid'];
        $coupon_user['is_end']            = 0;
        $coupon_user_rel = AisCouponUser::where($coupon_user)->find();
        //需要优惠的价格(分)
        $coupon_user_price = 0;
        if(!empty($coupon_user_rel)){
            if($money < $coupon_user_rel->howmuch){
                return false;
            }
            $config = AisConfig::getConfig($coupon_user['member_miniapp_id']);
            if(!empty($config->coupon_longtime) && ($coupon_user_rel->create_time + $config->coupon_longtime * 60 * 60) <= time()){
                return false;
            }
            if($coupon_user_rel->types){//折扣
                $coupon_user_price = $money - $money * ($coupon_user_rel->discount/10); 
            }else{//代金
                $coupon_user_price = $coupon_user_rel->price;
            }
        }
        $amount         = $money - $coupon_user_price;
        $data['price']  = $amount <= 0 ? 0.01 : $amount;
        $data['coupon'] = $coupon_user_rel;
        return $data;
    }


    /**
     * 微信买单收益分账
     * @param array $order  订单信息
     * @return void
     */
    public static function income($order,$allMoney,$flag){
        $store = AisStore::where(['id' => $order->store_id])->find();
        if(empty($store)){
            return;
        }
        $setting = AisConfig::getConfig($store->member_miniapp_id);
        $storeProfit = AisStore::where(['id' => $order->parent_store_id])->find();
        //没有分帐直接返回
        if($flag == 'N'){
            //如果是店铺直接会员  只扣手续费
            $order->parent_store_price = 0;
            $order->real = money($allMoney - $allMoney * 6 / 1000);
            return $order;
        }
        //平台所扣费率
        $charge = $store->charge ?? $setting->charge;
        $queen       = []; //分账队列参数
        //会员买单奖励
        if($flag == 'Y'  && !empty($setting) && !empty($setting->group_profit)){
            //平台所需扣除总额
            $profitMoney = money($allMoney * $charge);
            //平台承担手续费
            $charges =  money($allMoney * 6 / 1000);
            //扣除平台收费后所余
            $allMoney  = money($allMoney - $profitMoney);
            //用户的直接上级会员
            $level = SystemUserLevel::where(['user_id' => $order->uid,'level' => 1])->find();
            if(!empty($level)){
                //直接上级会员所属会员组
                $storeLevel_1 = AisStore::where(['manage_uid' => $level->parent_id])->find();
                $vipUser = AisVipUser::where(['member_miniapp_id' => $store->member_miniapp_id,'uid' => $level->parent_id,'is_lock' => 0])->find();
                $ex = $profitMoney;  //临时用
                //根据直接上级会员组配置开始分帐
                if(!empty($vipUser)){
                    $vip = AisVip::where(['member_miniapp_id' => $store->member_miniapp_id,'id' => $vipUser->vip_id,'is_lock' => 0])->find();
                    if(!empty($vip)){
                        $money = money($ex * $vip->pay_share_reward);
                        //会员余额增加
                        $bank = AisBank::where(['uid' => $level->parent_id])->find();
                        if(empty($bank)){
                            $bank = new AisBank;
                            $bank->uid = $level->parent_id;
                            $bank->member_miniapp_id = $order->member_miniapp_id;
                            $bank->money = 0;
                        }
                        $bank->money = $bank->money + $money;
                        $bank->save();
                        AisBill::add(['member_miniapp_id' => $store->miniapp_id,'store_id' => $store->id,'money' => $money,'uid' => $level->parent_id],'微信支付[奖励]');
                    }
                }
                //如果上级会员有店铺
                if(!empty($storeLevel_1)){
                    $level_2 = SystemUserLevel::where(['user_id' => $level->parent_id,'level' => 1])->find();
                    if(empty($level_2)){
                        $vipUser = AisVipUser::where(['member_miniapp_id' => $store->member_miniapp_id,'uid' => $level_2->parent_id,'is_lock' => 0])->find();
                        if(!empty($vipUser)){
                            $vip = AisVip::where(['member_miniapp_id' => $store->member_miniapp_id,'id' => $vipUser->vip_id,'is_lock' => 0])->find();
                            if(!empty($vip)){
                                $money = money($ex * $vip->pay_queue_reward);
                                //会员余额增加
                                $bank = AisBank::where(['uid' => $level_2->parent_id])->find();
                                if(empty($bank)){
                                    $bank = new AisBank;
                                    $bank->uid = $level_2->parent_id;
                                    $bank->member_miniapp_id = $order->member_miniapp_id;
                                    $bank->money = 0;
                                }
                                $bank->money = $bank->money + $money;
                                $bank->save();
                                AisBill::add(['member_miniapp_id' => $store->miniapp_id,'store_id' => $store->id,'money' => $money,'uid' => $level_2->parent_id],'微信支付[奖励]');
                            }
                        }
                    }
                }
            }
            //引荐买单奖励
            $profitMoney = 0;
            if(!empty($storeProfit)){
                $money = money($ex * $setting->group_profit);
                $profitMoney  = money($profitMoney - $money);
                $queen[] = [
                    'member_miniapp_id' => $storeProfit->member_miniapp_id,
                    'store_id'          => $storeProfit->id,
                    'uid'               => 0,
                    'mch_id'            => $storeProfit->mch_id,
                    'amount'            => $money * 100,
                    'transaction_id'    => $order->paid_no,
                    'out_order_no'      => $order->order_no,
                    'is_finish'         => 0,
                    'types'             => 1,
                    'msg'               =>'结算到商户号',
                ];
                AisStoreBill::add(['miniapp_id' => $storeProfit->member_miniapp_id,'uid' => $storeProfit->manage_uid,'store_id' => $storeProfit->id,'pay_uid' => $order['user_id'],'money' => $profitMoney],'引荐买单奖励'); //引荐商家账单
            }
            //平台收入
            $profitMoney = money($profitMoney - $charges);
            if(!empty($setting->config)){
                $queen[] = [
                    'member_miniapp_id' => $store->member_miniapp_id,
                    'store_id'          => $store->id,
                    'uid'               => 0,
                    'mch_id'            => 0,
                    'amount'            => $profitMoney * 100,
                    'transaction_id'    => $order->paid_no,
                    'out_order_no'      => $order->order_no,
                    'is_finish'         => 0,
                    'types'             => 2,
                    'msg'               => '结算到平台',
                ];
            }
            //分给商户
            $queen[] = [
                'member_miniapp_id' => $store->member_miniapp_id,
                'store_id'          => $store->id,
                'uid'               => 0,
                'mch_id'            => $store->mch_id,
                'amount'            => $allMoney * 100,
                'transaction_id'    => $order->paid_no,
                'out_order_no'      => $order->order_no,
                'is_finish'         => 0,
                'types'             => 1,
                'msg'               => '结算到商户号',
            ];
            $order->parent_store_price = $profitMoney;
            $order->real = $allMoney;
            AisQueen::createQueen($queen);
        }
        return $order;
    }

    //优惠券补贴
    public static function subsidy($order){
        $subsideze = AisCouponSubsidize::where(['member_miniapp_id' =>$order->member_miniapp_id,'coupon_id' => $order->conponUser->coupon_id])->find();
        if($subsideze){
//            $setting   =    AisConfig::getConfig($order->member_miniapp_id);
            //判断是否成功
            $is_success                       = false;
            $trade_no                         = $order->order_no . 'WE';
            $subsidezeBill = AisFundBill::where(['member_miniapp_id' =>$order->member_miniapp_id,'order_no' => $trade_no])->find();
            if(empty($subsidezeBill)){
                $subsidezeBill                    = new AisFundBill;
                $subsidezeBill->member_miniapp_id = $order->member_miniapp_id;
                $subsidezeBill->store_id          = $order->store_id;
                $subsidezeBill->uid               = $order->member_miniapp_id;
                $subsidezeBill->types             = 1;
                $subsidezeBill->money             = $subsideze->how_much;
                $subsidezeBill->order_no          = $trade_no;
            }
            if(!empty($order->store->user->official_uid) && $subsideze->how_much < 5000){
                    $app = WechatPay::doPay($order->member_miniapp_id,true);
                    $rel = $app->transfer->toBalance(['partner_trade_no' => $trade_no,'openid' => $order->store->user->official_uid,'check_name' => 'NO_CHECK','amount' => $subsideze->how_much*100,'desc' => '优惠券补贴']);
                    if ($rel['return_code'] === 'SUCCESS') {
                        if ($rel['result_code'] === 'SUCCESS') {
                            $is_success = true;
                            $subsidezeBill->state      = 1;
                            $subsidezeBill->message    = "优惠券补贴已结算到微信钱包";
                        }else{
                            $subsidezeBill->message    = $rel['err_code_des'];
                        }
                    }else{
                        $subsidezeBill->message    = $rel['return_msg'];
                    }
            }
            if(!$is_success){
                $subsidezeBill->state      = 2;
            }
            $subsidezeBill->update_time       = time();
            return $subsidezeBill->save();
        }else{
            return false;
        }
    }
}